package com.hualan.sfzy.controller.system;

import com.hualan.sfzy.entity.system.User;
import com.hualan.sfzy.service.system.UserService;
import com.hualan.sfzy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Mindy
 * @Date 2025年07月12日 上午11:19
 * @Version 1.0
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    // 新增
    @PostMapping("/user")
    public Result add(@RequestBody User user) {
        int num = userService.add(user);
        return num > 0 ? Result.success() : Result.error();
    }

    // 根据id删除
    @DeleteMapping("/user/{id}")
    public Result remove(@PathVariable Integer id) {
        int num = userService.remove(id);
        return num > 0 ? Result.success() : Result.error();
    }

    // 批量删除
    @DeleteMapping("/user")
    public Result removeBatch(Integer[] ids) {
        int num = userService.removeBatch(ids);
        return num > 0 ? Result.success() : Result.error();
    }

    // 修改
    @PutMapping("/user")
    public Result edit(@RequestBody User user) {
        int num = userService.edit(user);
        return num > 0 ? Result.success() : Result.error();
    }

    // 根据id查询
    @GetMapping("/user/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return Result.success(user);
    }

    // 分页带条件查询
    @GetMapping("/user/page")
    public Result findByPage(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                             User user) {
        Map<String, Object> map = userService.findByPage(pageNum, pageSize, user);
        return Result.success(map);
    }

    // 查询所有
    @GetMapping("/user")
    public Result find() {
        List<User> users = userService.find();
        return Result.success(users);
    }

    // 小程序登录
    @PostMapping("/user/login")
    public Result findByUsername(@RequestBody User user) {
        User login = userService.login(user);
        return Result.success(login);
    }

    // Vue登录
    @PostMapping("/admin")
    public Result findByAdmin(@RequestBody User user) {
        User login = userService.loginVue(user);
        return Result.success(login);
    }

    // 小程序更改密码
    @PostMapping("/user/pwd")
    public Result changePwd(@RequestBody Map<String, Object> requestMap) {
        Integer id = (Integer) requestMap.get("id");
        String oldPwd = (String) requestMap.get("oldPwd");
        String newPwd = (String) requestMap.get("newPwd");
        int num = userService.changePwd(id,oldPwd,newPwd);
        return num > 0 ? Result.success() : Result.error();
    }
}
